#include "PlatformTypeManager.h"
#include "DatabaseHandler.h"
#include <iostream>
#include <fstream>

PlatformTypeManager& PlatformTypeManager::getInstance() {
    // 创建静态单例实例
    static PlatformTypeManager instance;
    return instance;
}

bool PlatformTypeManager::initialize(const std::string& dbPath) {
    if (initialized) {
        // 已经初始化过
        std::cout << "PlatformTypeManager already initialized." << std::endl;
        return true;
    }
    
    std::cout << "Initializing PlatformTypeManager with database: " << dbPath << std::endl;
    
    // 检查文件是否存在
    std::ifstream dbFile(dbPath);
    if (!dbFile) {
        std::cerr << "Error: Database file does not exist: " << dbPath << std::endl;
        return false;
    }
    dbFile.close();
    
    // 创建数据库处理器
    DatabaseHandler dbHandler;
    
    std::cout << "Opening database..." << std::endl;
    // 打开数据库
    if (!dbHandler.open(dbPath)) {
        std::cerr << "Failed to open platform database: " << dbPath << std::endl;
        return false;
    }
    
    std::cout << "Database opened successfully. Loading platform types..." << std::endl;
    // 从数据库加载平台类型
    if (!dbHandler.loadPlatformTypes(platformTypes)) {
        std::cerr << "Failed to load platform types from database. Check if 'platform' table exists and contains data." << std::endl;
        // 不直接返回false，打印更多信息后再返回
    }
    
    // 关闭数据库连接
    std::cout << "Closing database connection..." << std::endl;
    dbHandler.close();
    
    // 即使加载失败也标记为已初始化，避免重复尝试加载
    initialized = true;
    
    std::cout << "Initialized PlatformTypeManager with " << platformTypes.size() << " platform types" << std::endl;
    if (platformTypes.empty()) {
        std::cerr << "Warning: No platform types were loaded from the database!" << std::endl;
        // 仍然返回true，因为初始化过程完成，即使没有数据
    }
    
    // 输出加载的平台类型
    for (const auto& [type, param] : platformTypes) {
        std::cout << "Loaded platform type: " << type << std::endl;
    }
    
    return true;
}

bool PlatformTypeManager::hasPlatformType(const std::string& platformType) const {
    return platformTypes.find(platformType) != platformTypes.end();
}

std::string PlatformTypeManager::getPlatformTypeDeclaration(const std::string& platformType) const {
    auto it = platformTypes.find(platformType);
    if (it != platformTypes.end()) {
        return it->second;
    }
    return ""; // 如果找不到，返回空字符串
}

const std::map<std::string, std::string>& PlatformTypeManager::getAllPlatformTypes() const {
    return platformTypes;
} 